/**
 * Created by linyi on 2019/3/11
 */
import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import { Form, Input, Icon, Button } from 'antd'

const { Item: FormItem } = Form
const hasErrors = fieldsErr =>
  Object.keys(fieldsErr).some(field => fieldsErr[field])

class SignIn extends React.Component {
  componentDidMount() {
    const {
      form: { validateFields }
    } = this.props
    validateFields()
  }

  onSubmit = e => {
    e.preventDefault()

    const {
      form: { validateFields },
      onSubmit: handleSubmit
    } = this.props
    validateFields((err, values) => {
      if (!err) {
        handleSubmit(values)
      }
    })
  }

  render() {
    const {
      form: { getFieldDecorator, getFieldsError },
      loading,
      errMsg,
      onForgetPWDClick
    } = this.props

    return (
      <section className="login--sign-in form-box">
        <header>
          <h1>欢迎登录</h1>
        </header>
        <Form onSubmit={this.onSubmit} className="login-common-form">
          <FormItem>
            {getFieldDecorator('username', {
              rules: [{ required: true }]
            })(
              <Input
                suffix={<Icon type="user" />}
                placeholder="请输入您的账号"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('password', {
              rules: [{ required: true }]
            })(
              <Input
                suffix={<Icon type="lock" />}
                placeholder="请输入您的密码"
                type="password"
              />
            )}
          </FormItem>
          <section className="action-box">
            <div className="err-box">
              <p>
                {errMsg && (
                  <Fragment>
                    <Icon type="exclamation-circle" theme="filled" />
                    {errMsg}
                  </Fragment>
                )}
              </p>
              <button
                type="button"
                className="btn-text"
                onClick={onForgetPWDClick}
              >
                忘记密码
              </button>
            </div>
            <Button
              type="primary"
              htmlType="submit"
              disabled={loading || hasErrors(getFieldsError())}
            >
              {loading ? '登录中' : '登录'}
            </Button>
          </section>
        </Form>
      </section>
    )
  }
}

SignIn.propTypes = {
  loading: PropTypes.bool.isRequired,
  errMsg: PropTypes.string.isRequired,
  // userData: PropTypes.objectOf(PropTypes.any).isRequired,
  onSubmit: PropTypes.func.isRequired,
  onForgetPWDClick: PropTypes.func.isRequired,
  form: PropTypes.objectOf(PropTypes.func).isRequired
}

export default Form.create()(SignIn)
